//
//  WJCollectionViewController.m
//  MarianasTrench
//
//  Created by wangjue on 16/3/19.
//  Copyright © 2016年 王爵. All rights reserved.
//

#import "WJCollectionViewController.h"

const CGFloat BackGroupHeight = 200;

@interface WJCollectionViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, retain) UITableView *tableView;/** 创建tableView*/
@property (nonatomic, retain) UIImageView *imageView;/** 大头像照片*/
@property (nonatomic, retain) UIView *backView;/** 背景*/
@property (nonatomic, retain) UILabel *titleLabel;/** 标题*/
@property (nonatomic, retain) NSMutableArray *modelArr;/** model数组 */
@property (nonatomic, retain) UIImageView *smallImageView;/** 小头像*/
@property (nonatomic, retain) UILabel *whiteLabel;/** 白色label的标题*/
@property (nonatomic, retain) UILabel *whiteDownLabel;/** 白色label下的标题*/
@property (nonatomic, assign) BOOL isUpdate; /** 判断是否为下拉*/
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, retain) NSMutableArray *tempArr;
@property (nonatomic, assign) NSInteger currentNum;
@end

@implementation WJCollectionViewController


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.num = 1;
        self.tempArr = [NSMutableArray array];
        self.modelArr = [NSMutableArray array];
        self.currentNum = 0;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"<" style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
    item.tintColor = [UIColor orangeColor];
    self.navigationItem.leftBarButtonItem = item;
    
    // 取消navagationbar下面的像素黑线
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView = (UIImageView *)obj;
                imageView.hidden = YES;
            }
        }
    }

   
    
    
    //创建tableView
    [self createTableView];
    
    //数据解析
    [self dataHandle];
    
    [self addFooter];
}

-(void)addFooter{
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //标记为上拉
        _num++;
        _isUpdate = YES;
        [self dataHandle];
    }];
}


-(void)itemAction:(UIBarButtonItem *)item{
    [self.navigationController popViewControllerAnimated:YES];
}

///数据解析
-(void)dataHandle{
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?device=iPhone",_str, _num];
    NSLog(@"1234%@", str);
    [APPTools GETWithURL:str par:nil success:^(id responseObject) {
        self.tempArr = [ListenModel modelHandleWithArray:responseObject[@"tracks"][@"list"]];
        for (ListenModel *model in _tempArr) {
            [_modelArr addObject:model];
        }
        
        [_tempArr removeAllObjects];
        
        
      
        
        //用label设置标题
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        _titleLabel.text = responseObject[@"album"][@"title"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor orangeColor];
        self.navigationItem.titleView = _titleLabel;
        
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 80, 100, 100)];
        [_imageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"album"][@"coverOrigin"]] placeholderImage:[UIImage imageNamed:@"no_network@3x"]];
        
        [_backView addSubview:_imageView];
        
        self.smallImageView = [[UIImageView alloc] initWithFrame:CGRectMake(120, 80, 30, 30)];
        [_smallImageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"album"][@"avatarPath"]] placeholderImage:[UIImage imageNamed:@"no_network@3x"]];
        _smallImageView.layer.cornerRadius = 15;
        _smallImageView.layer.masksToBounds = YES;
        _smallImageView.layer.borderWidth = 1;
        _smallImageView.layer.borderColor = [UIColor blackColor].CGColor;
        [_backView addSubview:_smallImageView];
        
        self.whiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 80, 200, 15)];
        _whiteLabel.textColor = [UIColor whiteColor];
        _whiteLabel.font = [UIFont systemFontOfSize:12];
        _whiteLabel.text = responseObject[@"album"][@"nickname"];
        [_backView addSubview:_whiteLabel];
        
        
        self.whiteDownLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 100, 200, 15)];
        _whiteDownLabel.textColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
        _whiteDownLabel.font = [UIFont systemFontOfSize:12];
        _whiteDownLabel.text = responseObject[@"album"][@"tags"];
        [_backView addSubview:_whiteDownLabel];
        
        
        NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"album"][@"intro"]];
        NSString *tempStr = @"在东亚大陆东面的西太平洋，自北向南、由小到大地散落着一串明珠，这就是美属马里亚纳群岛（联邦），英文简称CNMI，它几乎与中国、日本和韩国是等距离的。我们的音乐app就像如此这么强大.";
        NSString *newStr = [NSString stringWithFormat:@"%@%@", str, tempStr];
        LSPaoMaView *paoMaView = [[LSPaoMaView alloc] initWithFrame:CGRectMake(120, 150, 200, 15) title:newStr BackColor:[UIColor grayColor] textColor:[UIColor whiteColor] textFont:12];
        
        [_backView addSubview:paoMaView];

        
        
        
        [_tableView reloadData];
        
        [_tableView.mj_footer endRefreshing];
        
    } filed:^(NSError *error) {
        
    }];
}

///创建tableView
-(void)createTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.contentInset = UIEdgeInsetsMake(BackGroupHeight, 0, 0, 0);
    [self.view addSubview:_tableView];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, -BackGroupHeight, self.view.frame.size.width, BackGroupHeight)];
    _backView.backgroundColor = [UIColor grayColor];
    [_tableView addSubview:_backView];
    
    
   
    
    [_tableView registerClass:[CollectNextTableViewCell class] forCellReuseIdentifier:@"CollectNextTableViewCell"];
    
    
}



#pragma mark - tableView协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _modelArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CollectNextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectNextTableViewCell"];
    ListenModel *model = _modelArr[indexPath.row];
    cell.model = model;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"History" inManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
    //设置搜索的实体
    [fetchRequest setEntity:entity];
    
    //以某个字段排序 第二个参数 是否升旭
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"imgStr"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //搜索返回数据
    NSArray *fetchedObjects = [[CoreDataManager shareManager].managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error : %@", error);
    }
    
    
    ListenModel *model = _modelArr[indexPath.row];
    
    for (History *history in fetchedObjects) {
        
        if ([history.textLabel isEqualToString:model.title]) {
            _currentNum++;
            break;
        }
    }
    
    if (_currentNum == 0) {
        //前两行缩写，另一种创建方式
        History *history = [NSEntityDescription insertNewObjectForEntityForName:@"History" inManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
        
        history.imgStr = model.coverLarge;
        history.textLabel = model.title;
        history.textDownLabel = [NSString stringWithFormat:@"by%@", model.nickname];
        history.mp3Url = model.playUrl32;
     
        //保存
        [[CoreDataManager shareManager]saveContext];
    }
    
    MusicPlayerViewController *VC = [[MusicPlayerViewController alloc] init];
    VC.playMusicArr = [NSMutableArray arrayWithArray:_modelArr];
    VC.indexNum = indexPath.row;
    [self presentViewController:VC animated:YES completion:^{
        
    }];
    

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset = scrollView.contentOffset.y;
    
    CGFloat alpha = (yOffset +BackGroupHeight) / BackGroupHeight;
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00] colorWithAlphaComponent:alpha] ] forBarMetrics:UIBarMetricsDefault];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}


-(UIImage *)imageWithColor:(UIColor *)color{
    //描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    //开启为图上下文
    UIGraphicsBeginImageContext(rect.size);
    //获取位图的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //渲染上下文
    CGContextFillRect(context, rect);
    //从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    //结束上下文
    UIGraphicsEndImageContext();
    return theImage;

    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    // 取消navagationbar下面的像素黑线
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView = (UIImageView *)obj;
                imageView.hidden = NO;
            }
        }
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
